<?php
/**
 * Description of NewsController
 * @author : Yeu tinh
 * @since Oct 19, 2012
 */
class ProductController extends AppController {

    public $name = 'Product';
    public $uses = array('Catproduct', 'Product','Setting', 'News');
    public $components=array('Upload','Session');
    public $type = 'new';
    public $type_member = 'type_member';
    public $max_img = 1000;
    public $img_width = 0;//set width of image after upload
    public $img_height = 0;// 0 -> auto

    public function beforeFilter() {
        parent::beforeFilter();
    }



    public function add() {
        $this->set('no_slide', '12345');
        $this->checklogin();
        if (!empty($this->request->data)) {

            $this->Product->set($this->request->data);
            if ($this->Product->validates()) {

                //if($this->request->data['Product']['phanloai']==1) $this->request->data['Product']['choose2'] = 1;
                //if($this->request->data['Product']['phanloai']==0) $this->request->data['Product']['choose4'] = 1;

                if(isset($this->request->data['Product']['images'])){
                    $this->Upload->w = $this->img_width;
                    $this->Upload->h = $this->img_height;
                    $this->Upload->max_img = $this->max_img;
                    if(isset($this->request->data['Product']['name'])) $this->Upload->name = $this->request->data['Product']['name'];
                    $this->Upload->new = $this->request->data['Product']['images'];
                    $this->request->data['Product']['images'] = $this->Upload->Process();
                }

                $this->request->data['Product']['type'] = $this->type;
                $this->request->data['Product']['ytuong'] = 3; // set post member là ý tưởng thiết kế
                $this->request->data['Product']['type_member'] = $this->type_member;
                $this->request->data['Product']['user_member'] = $_SESSION['user_id'];

                $tmp = $this->Product->find('first',array('conditions'=>array('Product.type_member'=>$this->type_member),'order'=>array('Product.order'=>'DESC')));
                $this->request->data['Product']['order'] = $tmp['Product']['order'];
   
                if($this->request->data['Product']['phanloai']==0) $this->Product->save($this->request->data);
                if($this->request->data['Product']['phanloai']==1){
                    $this->request->data['News'] = $this->request->data['Product'];
                    $this->request->data['News']['cat_id'] = $this->request->data['Product']['cat_id1'];
                    $this->News->save($this->request->data['News']);
                }

                if(isset($this->notice['add_success'])) $this->Session->setFlash($this->notice['add_success'], 'default', array('class' => 'alert alert-success'));

                $this->loadModel('User');
                $this->User->id = $this->user_login['id'];
                $this->User->saveField('point',$this->user_login['point']+$this->Main_Setting['point_post']);

                if($this->request->data['Product']['phanloai']==1){
                    $tmp = $this->News->find('first',array('conditions'=>array('News.type_member'=>$this->type_member),'order' => 'News.id DESC'));
                    $this->redirect(DOMAIN.'chi-tiet/'.$tmp['News']['link'].'.html');
                }else{
                    $tmp = $this->Product->find('first',array('conditions'=>array('Product.type_member'=>$this->type_member),'order' => 'Product.id DESC'));
                    $this->redirect(DOMAIN.$tmp['Product']['link'].'.html');
                }
            } else {
                if(isset($this->notice['add_failed'])) $this->Session->setFlash($this->notice['add_failed'], 'default', array('class' => 'alert alert-error'));
            }
        }
        else{
            $this->request->data['Product']['cat_id'] = $this->Session->read('search_cat');
            $order = $this->Product->find('first',array('conditions'=>array('Product.type' => $this->type, 'Product.cat_id'=>$this->request->data['Product']['cat_id']),'order' => array('Product.order' => 'ASC')));
            if(isset($order['Product']['order'])){ $this->request->data['Product']['order'] = $order['Product']['order'] + 1;}else{$this->request->data['Product']['order'] = 0;}
            $this->request->data['Product']['status'] = 1;

        }

        $this->set('no_backlink','no_backlink');
    }


    public function edit($id) {
        $this->checklogin();
        $edit = $this->Product->findById($id);

        if($edit){
            if($edit['Product']['user_member']!=$this->user_login['id']){
                $this->Session->setFlash(lang('khong_the_sua_bai_nguoi_khac'), 'default', array('class' => 'alert alert-error'));
                $this->redirect($this->referer());
            }
        } else {
            $this->Session->setFlash(lang('bai_viet_khong_ton_tai'), 'default', array('class' => 'alert alert-error'));
            $this->redirect($this->referer());
        }

        if (!empty($this->request->data)) {

            $this->Product->set($this->request->data);
            if ($this->Product->validates()) {

                if(isset($this->request->data['Product']['images'])){
                    $this->Upload->w = $this->img_width;
                    $this->Upload->h = $this->img_height;
                    $this->Upload->max_img = $this->max_img;
                    if(isset($this->request->data['Product']['name'])) $this->Upload->name = $this->request->data['Product']['name'];
                    $this->Upload->new = $this->request->data['Product']['images'];
                    $this->request->data['Product']['images'] = $this->Upload->Process();
                }

                $this->request->data['Product']['type'] = $this->type;
                $this->request->data['Product']['ytuong'] = 3; // set post member là ý tưởng thiết kế
                $this->request->data['Product']['type_member'] = $this->type_member;
                $this->request->data['Product']['user_member'] = $_SESSION['user_id'];

                $tmp = $this->Product->find('first',array('conditions'=>array('Product.type_member'=>$this->type_member),'order'=>array('order'=>'DESC')));
                $this->request->data['Product']['order'] = $tmp['Product']['order'];

                $this->Product->save($this->request->data);

                if(isset($this->notice['add_success'])) $this->Session->setFlash($this->notice['add_success'], 'default', array('class' => 'alert alert-success'));

                $this->loadModel('User');
                $this->User->id = $this->user_login['id'];
                $this->User->saveField('point',$this->user_login['point']+$this->Main_Setting['point_post']);

                $tmp = $this->Product->find('first',array('conditions'=>array('Product.type_member'=>$this->type_member),'order' => 'Product.id DESC'));

                $this->redirect(DOMAIN.$tmp['Product']['link'].'.html');
            } else {
                if(isset($this->notice['add_failed'])) $this->Session->setFlash($this->notice['add_failed'], 'default', array('class' => 'alert alert-error'));
            }
        }
        else{
            $this->request->data = $this->Product->findById($id);
        }

        $this->set('no_backlink','no_backlink');
        $this->render('add');
    }

    public function delete($id){
        $this->checklogin();
        $delete = $this->Product->findById($id);


        $delete['Product']['user_member'];

        $this->user_login['id'];
        if($delete){
            if($delete['Product']['user_member']==$this->user_login['id']){
                $this->Product->delete($id);
                $this->Session->setFlash(lang('da_xoa_bai_viet'), 'default', array('class' => 'alert alert-error'));
            } else {
                $this->Session->setFlash(lang('khong_the_xoa_bai_nguoi_khac'), 'default', array('class' => 'alert alert-error'));
            }
        } else {
            $this->Session->setFlash(lang('bai_viet_khong_ton_tai'), 'default', array('class' => 'alert alert-error'));
        }


        $this->redirect($this->referer());
    }



    public function listpost($id = null){
        if(empty($id)){
            if(isset($this->notice['not_exits_link'])) $this->Session->setFlash($this->notice['not_exits_link'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(DOMAIN);
            exit;
        }
        $detailNews = $this->Catproduct->findByLink($id);
        if(empty($detailNews)){
            if(isset($this->notice['not_exits_link'])) $this->Session->setFlash($this->notice['not_exits_link'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(DOMAIN);
            exit;
        }

        //set title. keyword, decription
        if(!empty($detailNews['Catproduct']['title_seo'])) $this->set('title_for_layout', $detailNews['Catproduct']['title_seo']);
        else $this->set('title_for_layout', $detailNews['Catproduct']['name']);
        if($detailNews['Catproduct']['meta_key']) $this->set('keywords_for_layout', $detailNews['Catproduct']['meta_key']);
        if($detailNews['Catproduct']['meta_des']) $this->set('description_for_layout', $detailNews['Catproduct']['meta_des']);

        //set limmit
        $limit  = 8;

        $list_parent_id = $this->Catproduct->find('all', array(
            'fields' => array('id', 'name', 'name_eng', 'link'),
            'conditions' => array(
                'Catproduct.status' => 1,
                'Catproduct.parent_id' => $detailNews['Catproduct']['id']
            )
        ));
        $mnId = array();
        if($list_parent_id){
            $listtin = array();
            foreach($list_parent_id as $values){
                $cat_id = $this->multiMenuProduct($values['Catproduct']['id'], null);
                $cat_id[$values['Catproduct']['id']] = $values['Catproduct']['id'];
                $list = $this->Product->find('all', array(
                    'fields' => array('id', 'name', 'images', 'name_eng', 'link', 'shortdes', 'shortdes_eng', 'modified', 'user_id', 'like', 'view', 'cmt'),
                    'conditions' => array(
                      'Product.status' => 1,
                      'Product.cat_id' => $cat_id
                    ),
                    'order' => 'Product.order DESC, Product.modified DESC',
                    'limit' => '6'
                ));
                //gop ten cha + noi dung
                $listtin[] = array(
                    'id' => $values['Catproduct']['id'],
                    'name' => $values['Catproduct']['name'],
                    'name_eng' => $values['Catproduct']['name_eng'],
                    'link' => $values['Catproduct']['link'],
                    'list' => $list
                );
            }
            $this->set('listtin', $listtin);
            //------------------------------------------------------------------------------
        }else{
            $mnId = $this->multiMenuProduct($detailNews['Catproduct']['id'], null);
            $mnId[$detailNews['Catproduct']['id']] = $detailNews['Catproduct']['id'];
            $this->paginate = array(
                'conditions'=>array(
                    'Product.status'=>1,
                    'Product.cat_id'=>$mnId
                    ),
                    'limit' => $limit,
                    'order' => 'Product.order DESC'
                );
    	    $this->set('product', $this->paginate('Product',array()));
            //------------------------------------------------------------------------------
        }
        $this->set('cat', $detailNews);
        $this->set('no_slide', 'no_slide');
        $this->set('no_backlink', 'no_backlink');
    }

    public function detail($id = null) {
        if(empty($id)){
            if(isset($this->notice['not_exits_link'])) $this->Session->setFlash($this->notice['not_exits_link'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(DOMAIN);
            exit;
        }
        $detail = $this->Product->findByLink($id);
        if(empty($detail)){
            if(isset($this->notice['not_exits_link'])) $this->Session->setFlash($this->notice['not_exits_link'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(DOMAIN);
            exit;
        }

        //Set session luu view
        $post = $this->Session->read('post'.$detail['Product']['id']);
        if(empty($post)){
            $this->Session->write('post'.$detail['Product']['id'], $detail['Product']['id']);
            $this->Product->id = $detail['Product']['id'];
            $this->Product->saveField('view', ($detail['Product']['view'] + 1));

            //su ly cong slg view vao user fields sum_view
            $find_post_user = $this->Product->find('first', array(
                'fields' => array('id', 'user_member'),
                'conditions' => array(
                    'Product.type_member' => 'type_member',
                    'Product.user_member <>' => null,
                    'Product.id' => $detail['Product']['id']
                )
            ));
            if(!empty($find_post_user)){
                $this->loadModel('User');
                $find_user = $this->User->findById($find_post_user['Product']['user_member']);
                if(!empty($find_user)){
                    $this->User->id = $find_post_user['Product']['user_member'];
                    $this->User->saveField('sum_view', ($find_user['User']['sum_view'] + 1));
                }
            }
        }

        $cat = $this->Catproduct->findById($detail['Product']['cat_id']);
        $this->set('cat', $cat);
        $this->set('detail', $detail);
        $this->set('no_slide', 'no_slide');
        $this->set('no_backlink', 'no_backlink');

        //set kieu binh luan
        $this->set('id_post', $detail['Product']['id']);
        $this->set('type_post', 'post');

        //lay comment
        $this->loadModel('Cmt');
        $this->paginate = array(
            'conditions'=>array(
                'Cmt.status' => 1,
                'Cmt.comment_id' => null,
                'Cmt.foreign_id' => $detail['Product']['id']
                ),
                'limit' => 8,
                'order' => 'Cmt.id DESC'
            );
        $comment = $this->paginate('Cmt',array());

        $listcomt = array();
        foreach($comment as $value){
            $list = $this->Cmt->find('all', array(
                'conditions' => array(
                    'Cmt.status' => 1,
                    'Cmt.comment_id' => $value['Cmt']['id']
                ),
                'order' => 'Cmt.id ASC'
            ));
            //gop ten cha + noi dung
            $fullname = 'Not exits';
            if(!empty($value['User']['fullname'])) $fullname = $value['User']['fullname'];
            $listcomt[] = array(
                'id' => $value['Cmt']['id'],
                'content' => $value['Cmt']['content'],
                'created' => $value['Cmt']['created'],
                'fullname' => $fullname,
                'images' => $value['User']['images'],
                'list' => $list
            );
        }
        $this->set('comment', $comment);
        $this->set('listcomt', $listcomt);

        //set title, keyword, desciption
        if($detail['Product']['title_seo'] != null){
            if($detail['Product']['title_seo']) $this->set('title_for_layout', $detail['Product']['title_seo']);
        }else{
            if($detail['Product']['name']) $this->set('title_for_layout', $detail['Product']['name']);
        }
        if($detail['Product']['meta_key'])$this->set('keywords_for_layout', $detail['Product']['meta_key']);
        if($detail['Product']['meta_des'])$this->set('description_for_layout', $detail['Product']['meta_des']);

        //set limmit
        $limit  = 4;

		$tinlienquan = $this->Product->find('all', array(
            'fields' => array('name', 'name_eng', 'images', 'link', 'shortdes', 'shortdes_eng', 'modified'),
            'conditions'=>array(
                'Product.status'=>1,
                'Product.id <>' => $detail['Product']['id'],
                'Product.cat_id' => $detail['Product']['cat_id']
            ),
                'order' => 'Product.order DESC','limit' => $limit
        ));
	    $this->set('tinlienquan', $tinlienquan);
    }

    public function lienhe($id = null){
        $link = get_body_name($id);
        $abc = $this->Catproduct->findByLink($link);
        $this->set('cat', $abc);
        $this->set('title_for_layout', $abc['Catproduct']['name']);
        $setting = $this->Setting->find('first');
        $this->set('keywords_for_layout', $setting['Setting']['meta_key']);
        $this->set('description_for_layout', $setting['Setting']['meta_des']);
    }

    public function search(){
        if(isset($_POST['search'])){
            $title = $_POST['search'];
            $this->Session->write('timkiem', $title);
        }else{
            $title = $this->Session->read('timkiem');
        }
        $this->paginate = array(
            'conditions'=>array(
                'Product.status' => 1,
                'Product.type' => 'new',
                'Product.name LIKE' => '%' . $title . '%'
                ),
                'limit' => 15,
                'order' => 'Product.id DESC',
            );
            //pr($_POST['search']); die;
	    $this->set('listnews', $this->paginate('Product',array()));
        $this->set('cat', 'Tìm kiếm');
        $this->set('no_slide', 'no_slide');
        $this->set('no_backlink', 'no_backlink');
    }
    //
    public function multiMenuProduct($parentid = null, $trees = NULL) {
        $parmenu = $this->Catproduct->find('all', array(
            'conditions' => array(
                'Catproduct.parent_id' => $parentid,
                'Catproduct.status' => 1
            ),
            'order' => 'Catproduct.order ASC'
            ));
        if (count($parmenu) > 0) {
            foreach ($parmenu as $field) {
                $trees[$field['Catproduct']['id']] = $field['Catproduct']['id'];
                $trees = $this->multiMenuProduct($field['Catproduct']['id'], $trees);
            }
        }
        return $trees;
    }
}